import Vue from 'vue'
import Router from 'vue-router'
// import store from '../store/index.js'
import Home from '../views/Home'
import Login from '../views/Login'
import Register from '../views/Register'
import UserInfo from '../views/UserInfo'
import DomainInfo from '../views/DomainInfo'

Vue.use(Router)

const router = new Router({
    routes: [
      {
        path: '/',
        name: 'home',
        meta: {
          requireAuth: true,
        },
        component: Home,
        children: [
          {
            path: 'userInfo',
            name: 'userInfo',
            component: UserInfo,
          },
          {
            path: 'domainInfo',
            name: 'domainInfo',
            component: DomainInfo,
          },
        ],
      },
      {
        path: '/login',
        name: 'login',
        component: Login,
      },
      {
        path: '/register',
        name: 'register',
        component: Register,
      },
    ],
  });

// 设置路由拦截
// 在vue-router的全局钩子中设置拦截 
// 每个路由皆会的钩子函数
// to 进入 from 离开 next 传递
router.beforeEach((to, from, next) => {
    let token = localStorage.getItem('token')
    // to.meta.requireAuth
    if (to.meta.requireAuth) {
        //该 token
        if (token) {
            next()
        } else {
            next({
                path: '/login',
                query: {
                    redirect: to.fullPath
                }
            })
        }
    } else {
        next()
    }
})

export default router;